package com.fanketly.funacg2.data.paging

import android.util.Log
import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.fanketly.funacg2.data.TAG
import com.fanketly.funacg2.data.model.WorkList
import com.fanketly.funacg2.data.repo.AudioRepo
import com.fanketly.funacg2.utils.ToastUtils


class WorkBySearchPagingSource(private val name:String,private val repo: AudioRepo) :
    PagingSource<Int, WorkList.Work>() {
    override fun getRefreshKey(state: PagingState<Int, WorkList.Work>): Int? {
        return state.anchorPosition?.let {
            state.closestPageToPosition(it)?.prevKey?.plus(1)
                ?: state.closestPageToPosition(it)?.nextKey?.minus(1)
        }
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, WorkList.Work> {
        return try {
            val page = params.key ?: 1 //当前页，默认第一页
            val pageSize = params.loadSize //每页数据条数
            val repository = repo.getWorkListBySearch(name, page, pageSize) //获取的数据源
            val previousPage = if (page > 1) page - 1 else null //前一页
            val nextPage = if (repository.works.isNotEmpty()) page + 1 else null //下一页
            Log.d(TAG, "page=$page size=$pageSize")
            LoadResult.Page(repository.works, previousPage, nextPage)
        } catch (e: Exception) {
            ToastUtils.shortToast("${e.message}")
            LoadResult.Error(e)
        }
    }
}